package com.airticketbooking.service.serviceImpl;

import com.airticketbooking.common.constant.LevelConstant;
import com.airticketbooking.common.constant.StatusConstant;
import com.airticketbooking.common.utils.BeanUtils;
import com.airticketbooking.common.utils.UserContext;
import com.airticketbooking.po.Member;
import com.airticketbooking.po.Order;
import com.airticketbooking.po.Point;
import com.airticketbooking.mapper.MemberMapper;
import com.airticketbooking.mapper.OrderMapper;
import com.airticketbooking.mapper.PointMapper;
import com.airticketbooking.service.MemberService;
import com.airticketbooking.vo.MemberVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mr.J
 * @version 1.0.0
 * @date 2024/11/14
 * @desc
 */

@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {

	private final MemberMapper memberMapper;

	private final OrderMapper orderMapper;
	private final PointMapper pointMapper;

	@Override
	public MemberVO getMemberInfo() {


		Member member = memberMapper.getByUserId(UserContext.getUser().intValue());

		if (member == null) {
			throw new RuntimeException("用户未注册会员");
		}


		MemberVO memberVO = new MemberVO();

		BeanUtils.copyProperties(member, memberVO);
		memberVO.setTotalPoints(pointMapper.getPointByMemberId(member.getMemberId()).getTotalPoints());

		return memberVO;
	}

	@Override
	@Transactional
	public void registerMember() {


		Member member = memberMapper.getByUserId(UserContext.getUser().intValue());
//		判断用户是否已经注册过，如果已经注册过，则直接返回
		if (member != null) {
			throw new RuntimeException("用户已经注册过");
		}

//		查询用户总消费金额
		List<Order> orders = orderMapper.getByUserId(UserContext.getUser().intValue());

		BigDecimal totalAmount = new BigDecimal(0);
		for (Order order : orders) {
			if (order.getStatus() == StatusConstant.ORDER_FINISHED) {
				totalAmount = totalAmount.add(order.getActualAmountDue());
			}
		}

		//		判断用户是否满足注册条件
		if (totalAmount.compareTo(new BigDecimal(5000)) < 0) {
			throw new RuntimeException("消费金额不足5000，无法注册会员");
		}

//		插入注册信息
		// 插入注册信息
		member = new Member();
		member.setUserId(UserContext.getUser().intValue());
		member.setLevelId(LevelConstant.VIP);
		member.setJoinDate(LocalDateTime.now());

		memberMapper.add(member);

// 判断是否添加Member成功
		if (member.getMemberId() == null) {
			throw new RuntimeException("注册会员失败");
		}

//	插入积分信息

		Point point = new Point();
		point.setMemberId(member.getMemberId());
		point.setTotalPoints(0);
		pointMapper.add(point);

	}


}
